from loadstone.osmconverter import InmemoryConverter,Sqlite3UsingConverter
from optparse import OptionParser
import versionInfo,sys,codecs,time,platform,logging,os
from utils import * #locale tricks, gettext initialization ETC
from time import time,gmtime
try:
	import psyco
	psyco.full()
except ImportError:
	pass

def init_logging():
	logging.getLogger().setLevel(logging.DEBUG)
	fileLog=logging.FileHandler("log.txt","w","utf-8")
	fileLog.setLevel(logging.DEBUG)
	fileLog.setFormatter(logging.Formatter('%(levelname)s %(name)s - %(asctime)s\n%(message)s'))
	logging.getLogger('').addHandler(fileLog)
	consoleLog=logging.StreamHandler()
	consoleLog.setLevel(logging.DEBUG)
	consoleLog.setFormatter(logging.Formatter('%(levelname)-8s: %(name)s -- %(message)s'))
	logging.getLogger('').addHandler(consoleLog)
opts = OptionParser(usage = _("usage: %prog [options] OSMFILE LOADSTONEFILE"),version=versionInfo.version,description=_("This tool converts an OSM xml data  to a Loadstone GPS database format."))
opts.add_option("-p","--without-pois",action="store_true",default=False,help=_("Do not include  points of interest (shops, restaurants etc) in the result"))
#opts.add_option("-i","--no-intersections-only",action="store_true",default=False,help=_("By default, converter Includes only intersections, skipping noise. If it is not what you want, pass this option"))
opts.add_option("-m","--e-mail",type="string",help=_("Your e-mail adress, must be the same as in your loadstone settings"))
opts.add_option("-N","--preferred-names",type="string",action="append",help=_("You can append to stack of OSM tags which converter considers as a name tags. By default, list consists of ['name','description','operator']. It is order-sensitive."))
opts.add_option("-u","--transliterate-ukrainian",action="store_true",help=_("Apply the Ukrainian to Russian transliteration to point names if they contain native Ukrainian letters"))
opts.add_option('-f','--force-db-usage',action="store_true",help=_("Force usage of on-disk database even with small files to save memory"))
opts.add_option("-d","--intersection-delimiter",type="string",default=" X ",help=_("String sequence converter will insert between street names when constructing intersections. It is ' X ' by default"))
(options, args) = opts.parse_args()

if len(args) <2:
	opts.error(_("Not enough arguments given"))
initStdout()
init_logging()
if not options.e_mail:
	print _("Enter your e-mail adress:")
	options.e_mail=raw_input()
startTime=time()
try:
	with open(args[0],"rb") as input:
		Converter=Sqlite3UsingConverter if options.force_db_usage or os.fstat(input.fileno())[6]>50*1024*1024 else InmemoryConverter
		converter=Converter(input,options.e_mail,includePOIs=not options.without_pois,preferredNames=options.preferred_names,transliterateUkrainian=options.transliterate_ukrainian,intersectionDelimiter=options.intersection_delimiter)
	logging.debug(_("Writing output"))
	with codecs.open(args[1],"wb","utf-8") as f:
		converter.db.writeToBuffer(f)
	logging.info(_("Work took %d minutes and %d seconds")%(gmtime(time()-startTime).tm_min,gmtime(time()-startTime).tm_sec))
except:
	logging.error("",exc_info=True)
